package com.kchouse.myadapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.model.LatLng;
import com.kchouse.R;
import com.kchouse.StartActivity;
import com.kchouse.bean.BannerItem;
import com.kchouse.bean.MerchantItem;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.net.URISyntaxException;
import java.text.DecimalFormat;
import java.util.ArrayList;

public class HelpAdapter extends RecyclerView.Adapter<HelpAdapter.ViewHolder> {

    private Context context;
    private ArrayList<MerchantItem> datas = null;
    private boolean isfirst = true;
    private Intent intent = new Intent();

    public static final String PACKEGE_GAODE = "com.autonavi.minimap";
    public static final String PACKEGE_BAIDU = "com.baidu.BaiduMap";
    private LatLng endLatlng;
    private LatLng startLatlng;


    public HelpAdapter(Context context, ArrayList<MerchantItem> datas) {
        this.datas = datas;
        this.context = context;
    }

    //创建新View，被LayoutManager所调用
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {

        View view = null;
        ViewHolder vh = null;
        view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.lv_union_item, viewGroup, false);
        vh = new ViewHolder(view);
        return vh;
    }

    //将数据与界面进行绑定的操作
    @SuppressLint("ResourceAsColor")
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {

        final MerchantItem item = datas.get(position);
        if (TextUtils.isEmpty(item.getUrl())) {
            Picasso.with(context).load("null").error(R.mipmap.ic_loadingerror).into(viewHolder.iv_icon);
        } else {
            Picasso.with(context).load(item.getUrl()).error(R.mipmap.ic_loadingerror).into(viewHolder.iv_icon);
        }

        viewHolder.tv_name.setText(item.getName());

        if (item.isFollowStatus()) {
            viewHolder.tv_name.setTextColor(context.getResources().getColor(R.color.text_main));
            viewHolder.tv_name.setTypeface(Typeface.DEFAULT_BOLD);

        } else {
            viewHolder.tv_name.setTypeface(Typeface.DEFAULT);
            viewHolder.tv_name.setTextColor(context.getResources().getColor(R.color.colorblack));
        }


        viewHolder.tv_mobile.setText("电话：" + item.getContactMobile());
        viewHolder.tv_addr.setText("地址：" + item.getAddress());
        if (item.getVipStatus() == 1) {
            viewHolder.iv_vip.setVisibility(View.VISIBLE);
        } else {
            viewHolder.iv_vip.setVisibility(View.GONE);
        }
        if (item.getGuaranteeStatus() == 1) {
            viewHolder.iv_security.setVisibility(View.VISIBLE);
        } else {
            viewHolder.iv_security.setVisibility(View.GONE);
        }
        viewHolder.bt_navigation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                navigation("厦门","厦门","24.567153","118.054859");
                navigation("厦门", item.getName(), item.getLatitude(), item.getLongitude());
            }
        });
        viewHolder.bt_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callPhone(item.getContactMobile());

            }
        });

        double distance = item.getDistance() / 1000;
        DecimalFormat df = new DecimalFormat("0.##");
        String st = df.format(distance);
        viewHolder.tv_distance.setText(st + "km");
//        intiDistance(viewHolder, item);
    }



    /**
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *
     * @param phoneNum 电话号码
     */
    public void callPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        context.startActivity(intent);
    }
    /**
     * 距离计算
     *
     * @param viewHolder
     * @param item
     */
    private void intiDistance(ViewHolder viewHolder, MerchantItem item) {
        LatLng startLatlng = new LatLng(StartActivity.mLatitude, StartActivity.mLongitude);
        endLatlng = new LatLng(Double.valueOf(item.getLatitude()), Double.valueOf(item.getLongitude()));

        double distance = AMapUtils.calculateLineDistance(startLatlng, endLatlng);
        distance = distance / 1000;
        DecimalFormat df = new DecimalFormat("0.##");
        String st = df.format(distance);
        viewHolder.tv_distance.setText(st + "km");
    }


    /**
     * 判断是否安装目标应用
     *
     * @param packageName 目标应用安装后的包名
     * @return 是否已安装目标应用
     */
    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }

    /**
     * 城市名 位置名  目的地纬度 目的地经度(跳转到地图软件进行导航,优先选用高德地图,其次用百度地图)
     */
    private void navigation(String city, String position, String lat, String lon) {
        try {
            Intent intent = null;
            if (isInstallByread(PACKEGE_GAODE)) {
                //高德地图导航的代码
//                Toast.makeText(context, "打开高德地图", Toast.LENGTH_SHORT).show();
                intent = Intent.parseUri("androidamap://viewMap?sourceApplication=appname&poiname=" + position + "&lat=" + lat + "&lon=" + lon + "&dev=0", 0);
            } else if (isInstallByread(PACKEGE_BAIDU)) {
                //百度地图导航的代码
//                Toast.makeText(context, "打开百度地图", Toast.LENGTH_SHORT).show();
                intent = Intent.parseUri("intent://map/geocoder?location=" + lat + "," + lon + "&coord_type=gcj02&src=yourCompanyName|yourAppName#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end", 0);
            } else {
//                ToastUtils.getInstanc(context).showToast("未安装高德或者百度地图软件");
            }
            if (intent != null) {
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }


    //获取数据的数量
    @Override
    public int getItemCount() {
        return datas.size();
    }

    //自定义的ViewHolder，持有每个Item的的所有界面元素
    public class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView iv_icon;
        public TextView tv_name;
        public TextView tv_mobile;
        public TextView tv_addr;
        public TextView tv_distance;
        public ImageView iv_vip;
        public ImageView iv_security;
        public Button bt_navigation;
        public Button bt_phone;

        public ViewHolder(View view) {
            super(view);
            iv_icon = (ImageView) view.findViewById(R.id.iv_icon);
            tv_name = (TextView) view.findViewById(R.id.tv_name);
            tv_mobile = (TextView) view.findViewById(R.id.tv_mobile);
            tv_addr = (TextView) view.findViewById(R.id.tv_addr);
            tv_distance = (TextView) view.findViewById(R.id.tv_distance);
            iv_vip = (ImageView) view.findViewById(R.id.iv_vip);
            iv_security = (ImageView) view.findViewById(R.id.iv_security);
            bt_navigation = (Button) view.findViewById(R.id.bt_navigation);
            bt_phone = (Button) view.findViewById(R.id.bt_phone);

        }
    }


}
